package com.moss.cloud.auth.biz.listener;

import com.moss.cloud.auth.biz.events.LoginEvent;
import com.moss.cloud.auth.biz.service.IAuthorizationService;
import com.moss.cloud.auth.biz.service.ISysMenuService;
import com.moss.cloud.auth.biz.service.ISysUserService;
import com.moss.cloud.auth.biz.utils.UserAgentUtil;
import com.moss.cloud.common.base.model.po.SysUser;
import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.model.dto.UserLoginDTO;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author 瑾年
 * @data 2019/08/11 8:23
 * 用户授权失败 监听器
 */
@Component
@Slf4j
public class AuthorizationFailListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
    private final IAuthorizationService authorizationService;
    private final HttpServletRequest request;
    private final LoginEvent loginEvent;
    private final ISysUserService sysUserService;

    public AuthorizationFailListener(IAuthorizationService authorizationService,
                                     HttpServletRequest request,
                                     LoginEvent loginEvent,
                                     ISysUserService sysUserService) {
        this.authorizationService = authorizationService;
        this.request = request;
        this.loginEvent = loginEvent;
        this.sysUserService = sysUserService;
    }

    @Override
    public void onApplicationEvent(@NotNull AuthenticationFailureBadCredentialsEvent event) {
        if(!event.getAuthentication().getName().equals(Constant.DEF_CLIENT)){
            log.info("授权失败的处理方案-当前授权失败的用户名：{}",event.getAuthentication().getName());
            authorizationService.recordFailNum(event.getAuthentication().getName());
            SysUser sysUser = sysUserService.getUserByUsername(event.getAuthentication().getName());
            UserLoginDTO dto = UserAgentUtil.getFail(request, Constant.LOGIN_FAIL, event, sysUser);
            // 授权成功消息通知 1.登录日志消息或者同步下游服务数据消息
            // 2.发送登录成功的邮件或者短信提示消息
            loginEvent.sendUserLoginEvent(dto);
        }
    }
}
